package com.hrms.hrms_security.config;

import com.hrms.hrms_security.component.*;
import com.hrms.hrms_security.filter.CustomAuthenticationFilter;
import com.hrms.hrms_security.service.impl.UserDetailServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    CaptchaFilter captchaFilter;

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    JWTLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

//    @Bean
//    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
//        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
//        return jwtAuthenticationFilter;
//    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    private static final String[] URL_WHITELIST = {
            "/sysUsr/login",
            "/sysUsr/logout",
            "/sysUsr/captcha",
            "/sysUsr/register",
            "/favicon.ico"
    };

//    @Bean
//    public UserDetailsService userDetailsService(){
//        return new InMemoryUserDetailsManager(
//                User.withUsername("root").password("{noop}123").roles("ADMIN","USER").authorities("READ_INFO").build(),
//                User.withUsername("admin").password("{noop}123").roles("USER").build(),
//                User.withUsername("myz").password("{noop}123").authorities("READ_INFO").build()
//        );
//    }
    @Bean
    PasswordEncoder PasswordEncoder() {
        return new PasswordEncoder2();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                // 登录配置
//                .formLogin()
//                .loginProcessingUrl("//sysUsr/login") // 指定登录请求的URL
//                .successForwardUrl("/loginSuccess") // 登录成功后的跳转URL
//                .failureForwardUrl("/loginFailure") // 登录失败后的跳转URL
//                .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)

                // 禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 配置拦截规则
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated()
                // 异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)// 自定义无权访问处理器
                // 配置自定义的过滤器
                .and()
                //自定义登录拦截 用customAuthenticationFilter 替换 UsernamePasswordAuthenticationFilter
                .addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                // 验证码过滤器放在UsernamePassword过滤器之前
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)


        ;
    }

    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(loginSuccessHandler);
        filter.setAuthenticationFailureHandler(loginFailureHandler);
        // 可自定义登录接口请求路径
        filter.setFilterProcessesUrl("/sysUsr/login");
        filter.setAuthenticationManager(authenticationManagerBean());

        return filter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(new PasswordEncoder2());
    }
}
